package com.firemoss.magicbus.dto
{
	import com.firemoss.magicbus.messaging.fillter.BeforeFilter;
	import com.firemoss.magicbus.messaging.fillter.ResultFilter;
	
	import mx.collections.IList;
	import mx.rpc.events.ResultEvent;
	
	/**
	 * Invoked assembler methods on service method arguments / responses.  Assembles
	 * each element in a list individuall and delegates any other type to the assembler.
	 */
	public class AssemblerInvoker implements BeforeFilter, ResultFilter
	{
		
		public var assembler : DTOAssembler;
		public var disassembler : DTOAssembler;
		
		public function before( parameters : Array ) : Array
		{
			parameters[ 0 ] = assemblyDelegate( disassembler.disassemble, parameters[ 0 ] )
			
			return parameters
		}
		
		public function result( result : Object, event : ResultEvent ) : Object
		{
			return result == null ? null : assemblyDelegate( assembler.assemble, result )
		}

		public function assemblyDelegate( assemblyMethod : Function, source : Object ) : Object
		{
			var i : *
			
			if ( source is Array || source is IList )
			{
				for ( i = 0; i < source.length; i++ )
				{
					source[ i ] = assemblyMethod.apply( assembler, [ source[ i ] ] )
				}
			}
			else if ( source is Object )
			{
				source = assemblyMethod.apply( assembler, [ source ] )
			}
			
			return source
		}

	}
}